package com.luo.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.luo.model.ResultObj;
import com.luo.util.RedisUtil;
import com.luo.util.SmsTemplate;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 功能：获取验证码
 * 作者：Luo。
 * 日期：2024/3/7 11:41
 */
@WebServlet("/getCode")
public class GetCodeController extends HttpServlet {
	@Override
	protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
		ResultObj resultObj = new ResultObj();
		String phone = req.getParameter("phone");
		if (phone == null || "".equals(phone)) {
			resultObj.setCode("500");
			resultObj.setMsg("手机号不能为空");
			String jsonString = JSON.toJSONString(resultObj);
			resp.getWriter().write(jsonString);
			resp.getWriter().close();
			return;
		}
		String mobileRegEx = "^1[3,4,5,6,7,8,9][0-9]{9}$";
		Pattern pattern = Pattern.compile(mobileRegEx);
		Matcher matcher = pattern.matcher(phone);
		if (!matcher.matches()) {
			resultObj.setCode("500");
			resultObj.setMsg("移动手机号格式错误");
			String jsonString = JSON.toJSONString(resultObj);
			resp.getWriter().write(jsonString);
			resp.getWriter().close();
			return;
		}
		String code = RandomUtil.randomNumbers(6);
		try {
			// 调用接口发送验证码
			SmsTemplate.sendSms(phone, code);
			// 将验证码存入redis数据库中
			Jedis jedis = RedisUtil.getJedis();
			Map<String, String> hashData = new HashMap<>();
			hashData.put("code", code);
			hashData.put("phone", phone);
			jedis.hmset(phone, hashData);
			jedis.expire(phone, 300);
			jedis.close();
		} catch (Exception e) {
			e.printStackTrace();
			resultObj.setCode("500");
			resultObj.setMsg("未知异常");
			String jsonString = JSON.toJSONString(resultObj);
			resp.getWriter().write(jsonString);
			resp.getWriter().close();
			return;
		}
		resultObj.setCode("200");
		resultObj.setMsg("验证码发送成功");
		String jsonString = JSON.toJSONString(resultObj);
		resp.getWriter().write(jsonString);
		resp.getWriter().close();
	}
}
